%% 4. Curve Path Calculation Code

clear; clc;

%% LOAD SKELETONIZED VESSEL IMAGE
[fileName, filePath] = uigetfile('*', 'Select skeletonized vessel image');
if isequal(fileName, 0)
    disp('Selection cancelled.');
    return;
else
    vesselImage = imread(fullfile(filePath, fileName));
    if size(vesselImage, 3) == 3
        vesselImage = rgb2gray(vesselImage);
    end
    if ~islogical(vesselImage)
        vesselImage = imbinarize(vesselImage);
    end
    figure, imshow(vesselImage), title('Skeletonized Vessel Image');
end

%% LOAD START- AND ENDPOINT PAIRS FROM EXCEL
excelFile = 'StartEndPoints.xlsx'; % Replace with actual filename
if isfile(excelFile)
    data = readtable(excelFile);
    colNames = data.Properties.VariableNames;
    startCol = colNames{1};
    endCol = colNames{2};
    startPoints = data.(startCol);
    endPoints = data.(endCol);
else
    error('Excel file not found.');
end

startPoints = cellfun(@(s) sscanf(s, '(%d, %d)'), startPoints, 'UniformOutput', false);
endPoints = cellfun(@(s) sscanf(s, '(%d, %d)'), endPoints, 'UniformOutput', false);

%% CALCULATE STRAIGHT PATH LENGTH (EUCLIDEAN DISTANCE)
numPairs = length(startPoints);
results = cell(numPairs, 3);

for i = 1:numPairs
    x1 = startPoints{i}(1); y1 = startPoints{i}(2);
    x2 = endPoints{i}(1);   y2 = endPoints{i}(2);

    distance = round(sqrt((x2 - x1)^2 + (y2 - y1)^2));

    results{i, 1} = sprintf('(%d, %d)', x1, y1);
    results{i, 2} = sprintf('(%d, %d)', x2, y2);
    results{i, 3} = distance;

    if i == numPairs
        figure, imshow(vesselImage), title('Straight Line Path');
        hold on;
        plot([x1, x2], [y1, y2], 'r-', 'LineWidth', 2);
        plot(x1, y1, 'go', 'MarkerSize', 10, 'LineWidth', 2);
        plot(x2, y2, 'bo', 'MarkerSize', 10, 'LineWidth', 2);
        hold off;
    end
end

%% SAVE RESULTS TO EXCEL
outputData = cell(numPairs, 4);
for i = 1:numPairs
    startStr = results{i, 1};
    coords = sscanf(startStr, '(%d, %d)');
    xCoord = coords(1);

    outputData{i, 1} = xCoord;
    outputData{i, 2} = results{i, 1};
    outputData{i, 3} = results{i, 2};
    outputData{i, 4} = results{i, 3};
end

sortedData = sortrows(outputData, 1);
sortedData(:, 1) = [];

writecell([{'Startpoint', 'Endpoint', 'Straight Path'}; sortedData], 'StraightPaths.xlsx');
disp('Straight path data saved to Excel.');
